<template>
  <div class="cloud-order">
    <!-- 工具栏 -->
    <div class="head-container">
      <!-- 处方类型 -->
      <div class="cloud-order-top">
        <el-tabs
          class="cloud-order-tabs"
          @tab-click="onTabClick"
          v-model="activeDrug"
        >
          <template v-for="item in tabs">
            <el-tab-pane
              :label="item.text"
              :name="item.id"
              :key="item.id"
            />
          </template>
        </el-tabs>
        <div class="tools-buttons">
          <el-button-group class="filter-item">
            <el-button
              @click="onSwitch(0)"
              :class="cardButtonClass" 
              type="default"
            >
              图表
            </el-button>
            <el-button
              @click="onSwitch(1)"
              :class="listButtonClass" 
              type="default"
            >
              列表
            </el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 处方状态、待审方... -->
      <crudOperation>
        <div class="order-crud-left" slot="left">
          <el-radio-group 
            v-model="flag"
            @change="onChangeFlag"
          >
            <template v-for="item in flagList">
              <el-radio-button
                :label="item.id"
                :key="item.id" 
                class="order-crud-radio"
              >
                <span class="text">{{item.text}}</span>
                <!-- <span class="num" v-if="item.showNum">{{item.num}}</span> -->
                <span class="text" v-if="item.showNum">({{item.num}})</span>
              </el-radio-button>
            </template>
          </el-radio-group>
          <!-- <span class="filter-wait">待审方<span class="num">{{ waitNum }}</span>单</span> -->
        </div>
      </crudOperation>
      <div class="head-container-tools">
        <template v-if="crud.props.searchToggle">
          <el-row>
            <!-- 订单时间 -->
            <div class="order-form-item">
              <span>订单时间: </span>
              <el-date-picker
                v-model="query.orderTime"
                type="daterange"
                range-separator="至"
                size="small"
                class="filter-item charges-date-picker"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 240px"
              >
              </el-date-picker>
            </div>
            <!-- 支付时间 -->
            <div class="order-form-item">
              <span>支付时间: </span>
              <el-date-picker
                v-model="query.payTime"
                type="daterange"
                range-separator="至"
                size="small"
                class="filter-item charges-date-picker"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 240px"
              >
              </el-date-picker>
            </div>
            <!-- 订单编号 -->
            <div class="order-form-item">
              <el-input
                v-model="query.orderNo"
                placeholder="订单编号"
                style="width: 160px"
                class="filter-item"
                size="small"
              />
            </div>
            <!-- 患者名/手机号 -->
            <div class="order-form-item">
              <el-input
                v-model="query.patientName"
                placeholder="患者姓名或手机号"
                style="width: 160px"
                class="filter-item"
                size="small"
              />
            </div>
            <!-- 医生信息 -->
            <div class="order-form-item">
              <el-input
                v-model="query.docName"
                placeholder="医生姓名"
                style="width: 160px"
                class="filter-item"
                size="small"
              />
            </div>
            <div class="order-form-item">
              <rrOperation :crud="crud" @resetQuery="onResetQuery" />
            </div>
            <!-- 支付状态 -->
            <!-- <div class="order-form-item el-m-b-5">  
              <el-select
                v-model="status"
                @change="onChangeStatus"
                placeholder="支付状态"
                class="filter-item"
                clearable
              >
                <template v-for="item in statusList">
                  <el-option
                    :label="item.text"
                    :value="item.id"
                    :key="item.id"
                  />
                </template>
              </el-select>
            </div> -->
            <!-- 方案类型 -->
            <!-- <div class="order-form-item el-m-b-5">
              <el-select
                @change="crud.toQuery()"
                v-model="query.pstType"
                placeholder="方案类型"
                class="filter-item"
                clearable
              >
                <template v-for="item in pstTypeList">
                  <el-option
                    :label="item.text"
                    :value="item.id"
                    :key="item.id"
                  />
                </template>
              </el-select>
            </div> -->
          </el-row>
        </template>
      </div>
    </div>
    <!-- 表格 -->
    <el-table
      v-if="listSwitchValue === 1"
      v-loading="crud.loading"
      :data="crud.data"
      ref="table"
    >
      <el-table-column v-if="columns.visible('patientName')" label="患者姓名" prop="patientName">
        <template slot-scope="scope">{{ scope.row.patientName }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('patientSex')" label="性别" prop="patientSex">
        <template slot-scope="{row}">{{ getPatientSex(row.patientSex) }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('patientAge')" label="年龄" prop="patientAge">
        <template slot-scope="scope">{{ scope.row.patientAge }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('docName')" label="开方医生" prop="docName">
        <template slot-scope="scope">{{ scope.row.docName }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('orderTime')" label="开方时间" prop="orderTime" width="140">
        <template slot-scope="scope">{{ scope.row.orderTime }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('apiOrderNo')" label="订单编号" prop="apiOrderNo" width="155">
        <template slot-scope="scope">{{ scope.row.apiOrderNo }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('payStatus')" label="支付状态" prop="payStatus">
        <template slot-scope="scope">
          <template v-if="scope.row.payStatus == 0">
            <el-tag>未支付</el-tag>
          </template>
          <template v-if="scope.row.payStatus == 1">
            <el-tag type="success">已支付</el-tag>
          </template>
          <template v-if="scope.row.payStatus == 3">
            <el-tag type="danger">已部分退款</el-tag>
          </template>
          <template v-if="scope.row.payStatus == 4">
            <el-tag type="danger">已全部退款</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('payTime')" label="支付时间" prop="payTime" width="140">
        <template slot-scope="scope">{{ scope.row.payTime }}</template> 
      </el-table-column>
      <el-table-column v-if="columns.visible('totalFee')" label="支付金额" prop="totalFee">
        <template slot-scope="scope">{{ formatMoney(scope.row.totalFee - scope.row.cirulationCost, 2) }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('orderCondition')" label="处方状态" prop="orderCondition">
        <template slot-scope="{row}">
          <template
            v-if="row.orderCondition == 1 && row.payStatus != 4"
          >待审方
          </template>
          <template
            v-else-if="row.orderCondition == 2 && row.payStatus != 4"
          >调剂中
          </template>
          <template
            v-else-if="row.orderCondition == 4"
          >已完成
          </template>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('deliveryType')" label="取药方式" prop="deliveryType">
        <template slot-scope="scope">
          <template v-if="scope.row.deliveryType === 1">
            <span class="delivery-status status-1">邮寄</span>
          </template>
          <template v-if="scope.row.deliveryType === 2">
            <span class="delivery-status status-2">自取</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('remark')"
        :show-overflow-tooltip="true"
        label="订单备注"
        prop="remark"
        min-width="200"
      >
        <template slot-scope="{row}">{{ row.remark }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('pstType')" label="加工方式" prop="pstType">
        <template slot-scope="scope">
          <dosageForm
            :dosageForm="scope.row.infos[0].dosageForm"
            :pstType="scope.row.infos[0].pstType"
            :background="true"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <template v-for="item in scope.row.btns">
            <el-button
              :key="item.id"
              type="text" 
              @click="onRowHandle(item)"
            >{{ item.text }}</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 图表 -->
    <chartList
      v-if="listSwitchValue === 0"
      v-loading="crud.loading"
      @operate="onOperateRow"
      :data="crud.data"
    >
    </chartList>
    <!-- 分页组件 -->
    <pagination />
    <!-- 收费明细... -->
    <operateForm
      @refresh="refresh"
      ref="operateForm"
    >
    </operateForm>
    <!-- 处方打印... -->
    <printSend
      @refresh="onPrintRefresh"
      ref="printSend"
    />
  </div>
</template>

<script>
import { waitCheck, waitRefund } from '@/api/outpatientService/perscription';
import { getPatientSex, formatMoney } from "@/utils/index";
import CRUD, { presenter, header } from "@crud/crud";
import crudOperation from '@crud/CRUD.operation';
import operateForm from "./module/operateForm";
import rrOperation from "@crud/RR.operation";
import dosageForm from "./module/dosageForm";
import chartList from "./module/chartList";
import pagination from "@crud/Pagination";
import printSend from "../print";

let defaultCrud = CRUD({
  query: {
    pharmacyId: null,
    payStatus: null,
    orderType: 2,
    payTime: null,
    prescriptionType: null,
    orderTime: null,
    patientName: null,
    pstType: null,
    docName: null,
    orderCondition: 1,
    orderNo: null
  },
  hideColumns: ["patientSex","patientAge","pstType","orderTime", "apiOrderNo"],
  url: "api/recipel/getPrescriptions",
  queryOnPresenterCreated: false,
  sort: ['refund_flag,asc', 'pay_time,desc'],
  title: "门诊收费"
});

export default {
  name: "clinicCharges",
  mixins: [ presenter(defaultCrud), header() ],
  components: { 
    rrOperation,
    pagination,
    chartList,
    operateForm,
    dosageForm,
    printSend,
    crudOperation
  },
  computed: {
    listButtonClass() {
      if(this.listSwitchValue === 1) {
        return "active";
      }
      return "";
    },
    cardButtonClass() {
      if(this.listSwitchValue === 0) {
        return "active";
      }
      return "";
    }
  },
  data() {
    return {
      flagList: [
        {id: 0, text: "全部"},
        {id: 1, text: "待审方", showNum: true, num: 0},
        {id: 2, text: "调剂中"},
        {id: 4, text: "已完成"},
        {id: 34, text: "退款", showNum: true, num: 0},
      ],
      statusList: [
        {id: 0, text: "全部"},
        {id: 1, text: "已支付"},
        {id: 3, text: "部分退款"},
        {id: 4, text: "已退款"},
      ],
      pstTypeList: [
        {id: 0, text: "西药及中成药"},
        {id: 1, text: "饮片"},
        {id: 2, text: "颗粒"},
        {id: 3, text: "打粉"},
        {id: 4, text: "制丸"},
        {id: 5, text: "膏方"},
      ],
      tabs: [
        {id: "1", text: "中药饮片"},
        {id: "3", text: "配方颗粒"},
        {id: "2", text: "中成药"},
      ],
      listSwitchValue: 0,
      activeDrug: "1",
      status: 1,
      flag: 0
    }
  },
  created() {
    this.$store.dispatch("GetInfo").then(res => {
      this.query.pharmacyId = res.pharmacyId;
      this.crud.toQuery();
    });
  },
  mounted() {
    let date = new Date();
    let date2 = new Date(date.getTime() - 30 * 24 * 60 * 60 * 1000);
    if(!this.query.orderTime) {
      this.query.orderTime = [
        this._dateToString(date2),
        this._dateToString(date)
      ];
    }
    if(this.query.orderCondition == null) {
      this.flag = 0;
    } else {
      this.flag = this.query.orderCondition;
    }
    if(this.query.payStatus == null) {
      this.status = 0;
    } else {
      this.status = this.query.payStatus;
    }
    this.query.prescriptionType = this.activeDrug;

    // 消息中心
    this._messageHandle();
  },
  methods: {
    getPatientSex, formatMoney,
    [CRUD.HOOK.dataLoadSuccess](crud, data) {
      this._getWaitCheck();
      data.forEach(item => {
        item.btns = this._operateBtns(item);
      });
    },
    // 查看详情|打印
    onOperateRow(operate, id) {
      if(operate === 1) {
        // 部分退费处理
        this.$refs.operateForm.openRefundHandle(id);
      } else if(operate === 6) {
        // 打印
        this.$refs.printSend.open(id);
      } else {
        // 收费详情
        this.$refs.operateForm.open(operate, 99999);
      }
    },
    onResetQuery() {
      // 药品类型，处方状态不变
      switch(this.flag) {
        case 0:
          this.query.orderCondition = null;
          break;
        default:
          this.query.orderCondition = this.flag;
          break;
      }
      this.query.prescriptionType = this.activeDrug;

      // 订单时间
      let date = new Date();
      let date2 = new Date(date.getTime() - 7 * 24 * 60 * 60 * 1000);
      this.query.orderTime = [
        this._dateToString(date2),
        this._dateToString(date)
      ];
    },
    onChangeFlag() {
      switch(this.flag) {
        case 0:
          this.query.orderCondition = null;
          break;
        default:
          this.query.orderCondition = this.flag;
          break;
      }
      this.crud.toQuery();
    },
    onRowHandle(btn) {
      btn.handle.apply(this, btn.params)
    },
    onChangeStatus() {
      if(this.status == 0) {
        this.query.payStatus = null;
      } else {
        this.query.payStatus = this.status;
      }
      this.crud.toQuery();
    },
    // 打印页操作回调
    onPrintRefresh() {
      let operateForm = this.$refs.operateForm;
      this.refresh();
      if(operateForm.visible) {
        operateForm.refresh(null, false);
      }
    },
    onTabClick() {
      this.query.prescriptionType = this.activeDrug;
      this.crud.toQuery();
    },
    onSwitch(value) {
      this.listSwitchValue = value;
      if(value === 1) {
        this.$nextTick(() => {
          this.initTable();
        });
      }
    },
    refresh() {
      this.crud.refresh();
    },
    _operateBtns(row) {
      let { id, orderCondition, payStatus, refundFlag } = row;
      let res = [];

      switch(payStatus) {
        case 1: // 已支付
        case 3: // 部分退款
          if(refundFlag === 1) {
            res.push({ text: "去处理", handle: this.onOperateRow, params: [1,id], colSpan: 24 });
          } else if(orderCondition == 1) {
            // 待审方
            res.push({ text: "审方", handle: this.onOperateRow, params: [row], colSpan: 24 });
          } else if(orderCondition == 2) {
            // 调剂中
            res.push({ text: "调剂", handle: this.onOperateRow, params: [row], colSpan: 24 });
          } else {
            res.push({ text: "明细", handle: this.onOperateRow, params: [row], colSpan: 24 });
          }
          res.push({ text: "打印", handle: this.onOperateRow, params: [6, id], colSpan: 24 });
          break;
        case 4: // 已退款
          if(refundFlag === 1) {
            res.push({ text: "去处理", handle: this.onOperateRow, params: [row], colSpan: 24 });
          } else {
            res.push({ text: "明细", handle: this.onOperateRow, params: [row], colSpan: 24 });
          }
          break;
      }

      if(res.length > 1) {
        // 确定el-col组件的span属性值(图表用)
        let colSpan = 24 / res.length;
        res.forEach(item => {
          item.colSpan = colSpan;
        });
      }
      return res;
    },
    _success() {
      this.$notify({
        title: "操作成功",
        type: "success"
      });
      this.crud.toQuery();
    },
    _dateToString(date) {
      return date.getFullYear() + "-" + (date.getMonth()> 8 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1)) + "-" +(date.getDate() > 8 ? (date.getDate()) : "0" + (date.getDate()));
    },
    _getWaitCheck() {
      let prescriptionType = this.query.prescriptionType;
      waitCheck(prescriptionType).then(res => {
        this.flagList[1].num = res;
      });
      waitRefund(prescriptionType).then(res => {
        this.flagList[4].num = res;
      });
    },
    // 消息中心跳转来的
    _messageHandle() {
      let orderNo = this.$router.currentRoute.params.orderNo;
      
      if(orderNo) {
        this.onOperateRow({ id: orderNo });
      }
    }
  }
}
</script>

<style src="./style/index.css"></style>